﻿using Microsoft.Practices.Unity;
using Microsoft.Practices.ServiceLocation;
using Microsoft.TeamFoundation.Client;
using TfsMerge.Interface;
using TfsMerge.Service;
using System.Windows.Forms;

namespace TfsMerge
{
    static class Bootstrapper
    {
        public static bool Run()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += ApplicationThreadException;

            return ConfigureContainer();
        }

        static void ApplicationThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.ToString(), "Error...", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private static bool ConfigureContainer()
        {            
            var tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
            if (tpp.ShowDialog() == DialogResult.OK)
            {
                var project = tpp.SelectedProjects[0].Name;
                var tfs = tpp.SelectedTeamProjectCollection.Uri.OriginalString;

                var container = new UnityContainer()
                    .RegisterType<ITfs, Tfs>(new ContainerControlledLifetimeManager(), new InjectionConstructor(tfs, project));

                ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
                return true;
            }

            return false;
        }
    }
}
